package com.xian.ucenter.schedule;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.xian.ucenter.annotation.PostView;
import com.xian.ucenter.entities.Post;
import com.xian.ucenter.entities.Statistic;
import com.xian.ucenter.service.PostService;
import com.xian.ucenter.utils.ConstantUtil;
import com.xian.ucenter.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Set;

@Component
@Slf4j
public class BlogTask {
    @Resource
    private RedisUtil redisUtil;
    @Autowired
    private PostService postService;

    @Scheduled(cron = "0 0 1 * * *")
    @Transactional(rollbackFor = Exception.class)
    public void updatePostView() {
        Set<ZSetOperations.TypedTuple<String>> postViewList = redisUtil.zRangeWithScores(ConstantUtil.POST_VIEW_KEY, 0, -1);
        if (ObjectUtil.isNotNull(postViewList) && postViewList.size()>0) {
            postViewList.forEach(postView -> {
                LambdaUpdateWrapper<Post> courseUpdateWrapper = new LambdaUpdateWrapper<>();
                courseUpdateWrapper.eq(Post::getId,postView.getValue()).setSql("view_count = view_count + " + postView.getScore());
                postService.update(courseUpdateWrapper);
            });
        }
        redisUtil.delete(ConstantUtil.POST_VIEW_KEY);
    }
    @Scheduled(cron = "50 59 23 * * *")
    @Transactional(rollbackFor = Exception.class)
    public void updateQuestionView() {
        Long count = redisUtil.pfCount(ConstantUtil.WEB_VIEW_KEY);
        Statistic statistic = new Statistic();
        statistic.setCount(count);
        statistic.setDate(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        redisUtil.delete(ConstantUtil.WEB_VIEW_KEY);
    }
}
